package com.gamota.mobi;

import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import com.gamota.mobi.network.DownloadUpdateTask;
import com.gamota.mobi.network.IDownloadUpdateCallback;
import com.gamota.mobi.util.Utils;

public class SettingsActivity extends SherlockPreferenceActivity implements
		IDownloadUpdateCallback {

	public static final String KEY_AUTO_INSTALL = "_auto_install";
	public static final String KEY_DELTE_APK = "_delete_apk";
	public static final String KEY_ALLOW_PUSH = "_allow_push";
	public static final String ALLOW_LOAD_ALL_IMGs = "_allow_load_all_imgs";
	public static final String KEY_NOTIFY_UPDATE = "_allow_update";
	public static final String KEY_SET_LANGUAGE = "_set_language";
	public static final String DEFAULT_STORE = "_def_store";
	private SharedPreferences sharedPref;
	private CheckBoxPreference autoInstall;
	private CheckBoxPreference allowPush;
	private CheckBoxPreference allowLoadListImg;
	// private CheckBoxPreference deleteAPK;
	private CheckBoxPreference updateNotify;
	// private Preference clearCache;
	private boolean isRooted;
	public static final int REQUEST_CODE = 99;
	private String updateUri = "";
	// private LayoutInflater inflater;
	private int auto_language = 1;
	private int pre_auto_langue;
	private ListPreference list_languages;
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		String verInfo="Version: "+Utils.getVersion(this)+" build: "+Utils.getVersionCode(this);
		Toast.makeText(this, verInfo, Toast.LENGTH_LONG).show();
		addPreferencesFromResource(R.xml.preferences);
		getSupportActionBar().setTitle(R.string.setting);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		autoInstall = (CheckBoxPreference) findPreference("checkbox_auto_install");
		allowPush = (CheckBoxPreference) findPreference("checkbox_allow_push");
		updateNotify = (CheckBoxPreference) findPreference("checkbox_update_notify");
		allowLoadListImg = (CheckBoxPreference) findPreference("checkbox_load_list_img");
		isRooted = Utils.getStaticIsRooted(this);
		sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		if (!isRooted) {
			autoInstall.setEnabled(false);
		} else {
			autoInstall.setEnabled(true);
			autoInstall
					.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
						@Override
						public boolean onPreferenceChange(
								Preference preference, Object newValue) {
							sharedPref
									.edit()
									.putBoolean(KEY_AUTO_INSTALL,
											Boolean.valueOf(newValue + ""))
									.commit();
							return true;
						}
					});
		}
		allowPush
				.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
					@Override
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {
						// TODO Auto-generated method stub
						String value;
						if (String.valueOf(newValue).equals("true")) {
							value = "1";
						} else {
							value = "0";
						}
						sharedPref.edit().putString(KEY_ALLOW_PUSH, value)
								.commit();
						return true;
					}
				});
		allowLoadListImg
		.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference,
					Object newValue) {
				// TODO Auto-generated method stub
				String value;
				if (String.valueOf(newValue).equals("true")) {
					value = "1";
				} else {
					value = "0";
				}
				sharedPref.edit().putBoolean(ALLOW_LOAD_ALL_IMGs, (value=="1"?true:false)).commit();
				UILApplication.getInstance().setLoadAllImgs(value=="1"?true:false);
				return true;
			}
		});
		auto_language = sharedPref.getInt(SettingsActivity.KEY_SET_LANGUAGE, 1);
		pre_auto_langue = auto_language;
		list_languages = (ListPreference) findPreference("listLanguages");
		list_languages.setValue(String.valueOf(pre_auto_langue));
		list_languages
				.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
					@Override
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {
						String _newValue = newValue.toString();
						int value;
						if (_newValue.equals("1")) {
							value = 1;
							auto_language = 1;
							Log.e("language_set", "will be english");
						} else {
							value = 0;
							auto_language = 0;
							Log.e("language_set", "will be indonesian");
						}
						sharedPref.edit().putInt(KEY_SET_LANGUAGE, value)
								.commit();
						list_languages.setValue(String.valueOf(value));
						// /
						Locale locale;
						if (auto_language == 0) {
							locale = new Locale("vi");
						} else if (auto_language == 1) {
							locale = new Locale("en");
						} else {
							String _locale = getResources().getString(
									R.string.default_locale);
							locale = new Locale(_locale);
						}
						Configuration config = new Configuration();
						config.locale = locale;
						UILApplication app = UILApplication.getInstance();
						app.setConfig(config);
						list_languages.setSummary(getResources().getString(R.string.language_auto_detect));
						// /
//						if (pre_auto_langue != auto_language) {
//							Intent i = getBaseContext().getPackageManager()
//									.getLaunchIntentForPackage(
//											getBaseContext().getPackageName());
//							i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//							startActivity(i);
//						}
						return true;
					}
				});
		updateNotify
				.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
					@Override
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {
						// TODO Auto-generated method stub
						sharedPref
								.edit()
								.putString(KEY_NOTIFY_UPDATE,
										String.valueOf(newValue)).commit();
						return true;
					}
				});
		Log.e("onCreate-Settings", "pre_auto_langue" + pre_auto_langue + " & "
				+ auto_language);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	private Context getContext() {
		return this;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
			DownloadUpdateTask task = new DownloadUpdateTask(
					SettingsActivity.this);
			task.setDownloadCallback(this);
			task.execute(updateUri);
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (pre_auto_langue != auto_language) {
			Intent intent = new Intent();
			intent.putExtra("change_language", true);
			setResult(RESULT_OK, intent);
			finish();
		} else
			super.onBackPressed();
	}

	@Override
	public void onDownloadComplete(String path) {
		// TODO Auto-generated method stub
		Utils.installAPK(this, path);
		finish();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onDownloadError() {
		// TODO Auto-generated method stub

	}

}
